package com.glut.campusrepair.service;

import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Service
public class EmailService {

    private final String from = "wensheng.huang@qq.com";
    private final String password = "ljyxxpmkamxwghdd";

    public boolean sendResetPasswordEmail(String to, String code) {
        String host = "smtp.qq.com";
        int port = 587;

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", String.valueOf(port));
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        properties.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");

        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("重置密码邮件");

            // 邮件内容
            String emailBody =
                    "尊敬的用户，\n\n" +
                            "您收到这封邮件是为了重置您的密码。\n\n" +
                            "您的验证码是： " + code + "\n\n" +
                            "请在五分钟内使用此验证码完成密码重置。如果验证码过期，请重新申请重置密码。\n\n" +
                            "如果您没有请求密码重置，请忽略此邮件。\n\n" +
                            "感谢您的使用！\n\n" +
                            "祝好，\n" +
                            "大学报修系统";

            message.setText(emailBody, "UTF-8");

            Transport.send(message);
            return true;
        } catch (MessagingException mex) {
            mex.printStackTrace();
            return false;
        }
    }
}
